using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Outlook;

namespace Test {
	class EmailExtract {
		static void MainX() {
			MAL dal=new MAL();
			dal.NonQry("drop table IF EXISTS mail");
			dal.NonQry("create table mail(id int auto_increment primary key,mto varchar(500),subject varchar(200),topic varchar(200),sent datetime,body text)");
			//dal.NonQry("truncate table mail");dal.NonQry("drop table mail");
			Microsoft.Office.Interop.Outlook.Application app=null;
			Microsoft.Office.Interop.Outlook._NameSpace ns=null;
			Microsoft.Office.Interop.Outlook.PostItem item=null;
			Microsoft.Office.Interop.Outlook.MAPIFolder inbox=null;
			Microsoft.Office.Interop.Outlook.MAPIFolder subFolder=null;

			try
			{
				app=new Microsoft.Office.Interop.Outlook.Application();
				ns=app.GetNamespace("MAPI");
				ns.Logon(null,null,false,false);

				inbox=ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
				subFolder=inbox.Folders[1]; //folder.Folders[1]; also works
				Console.WriteLine("Folder Name: {0}, EntryId: {1}",inbox.Name,inbox.EntryID);
				Console.WriteLine("Num Items: {0}",inbox.Items.Count.ToString());

				for(int i=inbox.Items.Count;i>0;i--)
					//foreach(object obj in inbox.Items)

					if(inbox.Items[i] is MailItem)
					{
						MailItem mail=inbox.Items[i] as MailItem;
						Console.WriteLine(mail.SentOn.ToString("yyyy-MM-dd HH:mm:ss")+" - "+mail.ReceivedTime.ToString("yyyy-MM-dd HH:mm:ss")+" - "+mail.Subject);
						Console.WriteLine(mail.ConversationTopic);
						//if(mail.To=="Ziarek, Piotr")
						dal.NonQry("insert ignore into mail(subject,topic,sent,body,mto)values('{0}','{1}','{2:yyyy-MM-dd HH:mm:ss}','{3}','{4}')",(mail.Subject??"").Replace("'","''"),(mail.ConversationTopic??"").Replace("'","''"),mail.SentOn,(mail.Body??"").Replace("'","''"),mail.To.Replace("'","''"));
					}
					else
					{
						//Console.WriteLine(obj.GetType());
					}


				//for(int i=1;i<=subFolder.Items.Count;i++)
				//{
				//  item=(Microsoft.Office.Interop.Outlook.MailItem)subFolder.Items[i];
				//  Console.WriteLine("Item: {0}",i.ToString());
				//  Console.WriteLine("Subject: {0}",item.Subject);
				//  Console.WriteLine("Sent: {0} {1}",item.SentOn.ToLongDateString(),item.SentOn.ToLongTimeString());
				//  Console.WriteLine("Categories: {0}",item.Categories);
				//  Console.WriteLine("Body: {0}",item.Body);
				//  Console.WriteLine("HTMLBody: {0}",item.HTMLBody);
				//}
			}
			catch(System.Runtime.InteropServices.COMException ex)
			{
				Console.WriteLine(ex.ToString());
			}



		}
	}
}
